import { SET_MENUS, CLEAR_MENUS, SELECT_MENU } from '../constants'

function setExpanded(menus, selectedMenu) {
  let parent = menus.find(m => m.menuId === selectedMenu.parentId)
  if (parent) {
    parent.expanded = true
    setExpanded(menus, parent)
  }
}

const menuReducer = (state = [], action) => {
  switch (action.type) {
    case SET_MENUS:
      return action.menus
    case CLEAR_MENUS:
      return []
    case SELECT_MENU:
      //clone new menus
      let menus = state.map(m => ({...m}))
      //set selected/expanded = false
      menus.forEach(m => {
        m.selected = false
        m.expanded = false
      })
      //set selectedMenu.selected/expanded = true
      let selectedMenu = menus.find(m => m.menuId === action.menuId)
      if (selectedMenu) {
        selectedMenu.selected = true
        setExpanded(menus, selectedMenu)
      }
      return menus
    default:
      return state
  }
}

export default menuReducer
